/**
 * 
 */
package com.hand.cloud.b2b.daos.impl;

import de.hybris.platform.b2b.model.B2BCustomerModel;
import de.hybris.platform.commerceservices.customer.CustomerEmailResolutionService;
import de.hybris.platform.commerceservices.model.ContactEmailAttribute;
import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.servicelayer.exceptions.ModelSavingException;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hand.cloud.b2b.daos.CustomerDAO;


/**
 * @author StephenWang
 * @time Aug 6, 2014 3:57:59 PM
 * 
 */
@Component(value = "customerDAO")
public class DefaultCustomerDAO implements CustomerDAO
{
	Logger LOG = Logger.getLogger(DefaultCustomerDAO.class);

	@Autowired
	private ModelService modelService;

	@Autowired
	private FlexibleSearchService flexibleSearchService;

	@Autowired
	private CustomerEmailResolutionService customerEmailResolutionService;

	/**
	 * 创建客户
	 * 
	 * @return
	 */
	@Override
	public CustomerModel createCustomer()
	{
		CustomerModel customer = this.modelService.create(CustomerModel.class);
		customer.setCustomerID("Customer_" + new Date().getTime());
		customer.setName("孤独的_" + new Date().getTime());

		// 动态字段创建
		ContactEmailAttribute email = new ContactEmailAttribute();
		email.setCustomerEmailResolutionService(customerEmailResolutionService);
		customer.setUid("Customer_" + new Date().getTime());

		try
		{
			this.modelService.save(customer);

			LOG.info("customer:uid" + customer.getUid() + " customer:pk" + customer.getPk());
		}
		catch (ModelSavingException e)
		{
			e.printStackTrace();
			return null;
		}

		return customer;
	}

	/**
	 * 通过客户ID查询客户
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public CustomerModel getCustomerByUid(String uid)
	{
		B2BCustomerModel customer = new B2BCustomerModel();
		customer.setUid(uid);

		try
		{
			customer = this.flexibleSearchService.getModelByExample(customer);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}

		return customer;
	}

}
